package com.oj.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.oj.entity.Message;
import com.oj.entity.Tags;
import com.oj.entity.Tagsview;
import com.oj.mapper.PrivilegeMapper;
import com.oj.mapper.TagsMapper;
import com.oj.mapper.TagsviewMapper;
import com.oj.service.impl.I18nService;
import com.oj.util.CodeMsg;
import com.oj.util.DateUtil;
import com.oj.util.Html2Text;
import com.oj.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Slf4j
@Controller
@RequestMapping
public class TagsController {
    @Autowired
    private I18nService i18nService;

    @Autowired
    private TagsMapper tagsMapper;

    @Autowired
    private TagsviewMapper tagsViewMapper;

    @Autowired
    private PrivilegeMapper privilegeMapper;

    @ResponseBody
    @PostMapping(value = "/api/tags/query")
    public Result apiTagQuery(String q){
        Tags tag = tagsMapper.queryByName(q);
        if (tag == null) {
            return Result.error(0, null);
        }
        tag.setCreateFriendlyDate(DateUtil.toFriendlyDate(tag.getIndate()));
        List<Tagsview> problems = tagsViewMapper.queryProblemsByTagId(tag.getTag_id());
        List<Tagsview> topics = tagsViewMapper.queryTopicsByTagId(tag.getTag_id());
        tag.setProblem_count(problems.size());
        tag.setTopic_count(topics.size());
        Map m = new HashMap();
        m.put("tag", tag);
        m.put("tag_problems_name", i18nService.getMessage("tag_problems"));
        m.put("tag_topics_name", i18nService.getMessage("tag_topics"));
        m.put("tag_post_name", i18nService.getMessage("tag_create_at"));
        return Result.success(m);
    }

    @ResponseBody
    @RequestMapping(value = {"/api/tags/search"}, method = RequestMethod.GET)
    public Result<List> apiTagsSearch(String q){
        List<Tags> tags = tagsMapper.search(q);
        List<String> tagsList = new ArrayList<String>();
        for (Tags t:tags) {
            tagsList.add(t.getName());
        }
        return Result.success(tagsList);
    }

    @ResponseBody
    @RequestMapping(value = {"/api/tags/filter"}, method = RequestMethod.GET)
    public Result apiTagsFilter(String q){
        Map m = new HashMap();
        List<Tags> tags = tagsMapper.search(q);
        for (Tags tag:tags) {
            tag.setCreateFriendlyDate(DateUtil.toFriendlyDate(tag.getIndate()));
            List<Tagsview> problems = tagsViewMapper.queryProblemsByTagId(tag.getTag_id());
            List<Tagsview> topics = tagsViewMapper.queryTopicsByTagId(tag.getTag_id());
            tag.setProblem_count(problems.size());
            tag.setTopic_count(topics.size());
        }

        m.put("tagList", tags);
        m.put("tag_problems_name", i18nService.getMessage("tag_problems"));
        m.put("tag_topics_name", i18nService.getMessage("tag_topics"));
        m.put("tag_post_name", i18nService.getMessage("post"));
        m.put("tags_name", i18nService.getMessage("tags"));
        return Result.success(m);
    }

    @RequestMapping(value = {"/tags",
            "/tags/page/{pageNum}"}, method = RequestMethod.GET)
    public ModelAndView tags(@PathVariable(value = "pageNum",required = false)Integer pageNum,
                               @RequestParam(value = "pageSize",required = false, defaultValue = "50")Integer pageSize){
        if (pageNum == null) {
            pageNum = 1;
        }
        PageHelper.startPage(pageNum,pageSize);
        Page<Tags> tags = tagsMapper.findByPaging();
        for (Tags tag: tags) {
            tag.setCreateFriendlyDate(DateUtil.toFriendlyDate(tag.getIndate()));
            List<Tagsview> problems = tagsViewMapper.queryProblemsByTagId(tag.getTag_id());
            List<Tagsview> topics = tagsViewMapper.queryTopicsByTagId(tag.getTag_id());
            tag.setProblem_count(problems.size());
            tag.setTopic_count(topics.size());
        }
        PageInfo<Tags> pageInfo = new PageInfo<>(tags);
        ModelAndView mv = new ModelAndView();
        mv.addObject("pageInfo", pageInfo);
        mv.setViewName("tag/tags.html");
        return mv;
    }


    @ResponseBody
    @PostMapping(value = "/api/tag/post")
    public Result postTags(@RequestParam Map<String, Object> map, HttpServletRequest request){
        if (request.getSession().getAttribute("session_username") == null) {
            return Result.error(CodeMsg.USER_NOT_LOGIN.locale());
        }
        log.info(map.toString());
        if (map.get("type") == null) {
            return Result.error(CodeMsg.PARAM_INVALID.locale());
        }

        if (map.get("type").toString().equals("edit")) {
            return editTag(map, request);
        }
        if (map.get("type").toString().equals("new")) {
            return newTag(map, request);
        }
        return Result.success();
    }
    public Result editTag(Map<String, Object> map, HttpServletRequest request) {
        try {
            if (map.get("name") == null || map.get("name").toString().length() == 0
                    || map.get("description") == null || map.get("description").toString().trim().length() == 0) {
                return Result.error(CodeMsg.INPUT_CONTENT_NULL.locale());
            }
            String name = map.get("name").toString();
            Tags tags = tagsMapper.queryByName(name);
            if (tags == null) {
                return Result.error(CodeMsg.PARAM_INVALID.locale());
            }
            tags.setDescription(map.get("description").toString());

            String username = request.getSession().getAttribute("session_username").toString();
            if (username == null) {
                return Result.error(CodeMsg.USER_NOT_LOGIN.locale());
            }
            if (privilegeMapper.query(username, "HEAD") == null
                    && privilegeMapper.query(username, "ADMIN") == null) {
                return Result.error(CodeMsg.ADMIN_NO_ACCESS.locale());
            }

            if (tagsMapper.update(tags)) {
                return Result.success();
            }
        } catch (Exception e) {
            log.error("saveTags Exception."+ e.getMessage());
        }
        return Result.error(CodeMsg.INNER_FAULT.locale());
    }
    public Result newTag(Map<String, Object> map, HttpServletRequest request) {
        try {
            if (map.get("name") == null || map.get("name").toString().length() == 0
                    || map.get("description") == null || map.get("description").toString().trim().length() == 0) {
                return Result.error(CodeMsg.INPUT_CONTENT_NULL.locale());
            }
            String name = map.get("name").toString();
            Tags tags = tagsMapper.queryByName(name);
            if (tags != null) {
                return Result.error(CodeMsg.TAG_IS_EXIST.locale());
            }

            String username = request.getSession().getAttribute("session_username").toString();
            if (username == null) {
                return Result.error(CodeMsg.USER_NOT_LOGIN.locale());
            }
            if (privilegeMapper.query(username, "HEAD") == null
                    && privilegeMapper.query(username, "ADMIN") == null) {
                return Result.error(CodeMsg.ADMIN_NO_ACCESS.locale());
            }

            tags = new Tags();
            tags.setName(name);
            tags.setDescription(map.get("description").toString());
            tags.setCreate_user(username);
            tags.setIndate(new Date());
            if (tagsMapper.insert(tags)) {
                return Result.success();
            }
        } catch (Exception e) {
            log.error("newTags Exception."+ e.getMessage());
        }
        return Result.error(CodeMsg.INNER_FAULT.locale());
    }
}
